using System;
using System.Collections.Generic;
using dbvc.data;
using dbvc.Queries;

namespace dbvc.context.Script
{
    public class AttachScript
    {
        private db_activity Activity;
        private db_user Principal;
        private IList<db_script> Scripts;
        private db_version Version;

        public AttachScript(db_user principal, db_version ver, IList<db_script> srs)
        {
            Attach(principal, ver, srs);
        }

        public AttachScript(db_user principal, db_version ver, db_script src)
        {
            Attach(principal, ver, new[] {src});
        }

        public AttachScript(db_user principal, int version, db_script src)
        {
            var v = VersionQuery.Get(version);
            Attach(principal, v, new[] { src } );
        }

        private void Attach(db_user p, db_version v, IList<db_script> s)
        {
            Principal = p;
            Version = v;
            Scripts = s;
        }

        public void Execute()
        {
            foreach (db_script s in Scripts)
            {
                var vs = new db_version_script {id_script = s.id, id_version = Version.id};
                Activity = new db_activity
                               {action = "attach to version", datestamp = DateTime.Now, userstamp = Principal.name};

                GenericQuery<db_version_script>.Create(vs);
                GenericQuery<db_activity>.Create(Activity);
            }
        }
    }
}